package com.h.blog.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.h.blog.common.constant.Constants;
import com.h.blog.common.exception.BlogException;
import com.h.blog.common.unit.BeanTransUnits;
import com.h.blog.common.unit.JwtUnits;
import com.h.blog.common.unit.SecurityUnits;
import com.h.blog.mapper.UserInfoMapper;
import com.h.blog.pojo.dataobject.BlogInfo;
import com.h.blog.pojo.dataobject.UserInfo;
import com.h.blog.pojo.request.UserLoginRequest;
import com.h.blog.pojo.response.UserInfoResponse;
import com.h.blog.pojo.response.UserLoginResponse;
import com.h.blog.service.BlogService;
import com.h.blog.service.UserService;
import jakarta.annotation.Resource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserInfoMapper userInfoMapper;

    @Resource(name = "blogServiceImpl")
    private BlogService blogService;

    @Override
    public UserLoginResponse checkPassword(UserLoginRequest userLoginRequest) {
        QueryWrapper<UserInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda()
                .eq(UserInfo::getUserName,userLoginRequest.getUserName())
                .eq(UserInfo::getDeleteFlag, Constants.BLOG_NORMAL);
        UserInfo userInfo = userInfoMapper.selectOne(queryWrapper);
        if (userInfo == null) {
            // 用户不存在
            throw new BlogException("用户不存在");
        }
//        if (!userLoginRequest.getPassword().equals(userInfo.getPassword())) {
//            // 密码不正确
//            throw new BlogException("用户密码错误");
//        }
        if(!SecurityUnits.verify(userLoginRequest.getPassword(),userInfo.getPassword())) {
            // 密码不正确
            throw new BlogException("用户密码错误");
        }
        // 密码存在
        Map<String,Object> map = new HashMap<>();
        map.put("userId",userInfo.getId());
        map.put("userName",userInfo.getUserName());
        String token = JwtUnits.genToken(map);
        return new UserLoginResponse(userInfo.getId(),token);
    }

    @Override
    public UserInfoResponse getUserInfo(Integer userId) {
        QueryWrapper<UserInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda()
                .eq(UserInfo::getId,userId)
                .eq(UserInfo::getDeleteFlag,Constants.BLOG_NORMAL);
        UserInfo userInfo = userInfoMapper.selectOne(queryWrapper);
        // 进行转型，转成需要的返回的数据
        return BeanTransUnits.trans(userInfo);
    }

    @Override
    public UserInfoResponse getAuthorInfo(Integer blogId) {
        // 1、根据blogId到blog中获取博客的作者的相关信息
        BlogInfo blogInfo = blogService.getBlogInfo(blogId);
        if (blogInfo == null || blogInfo.getUserId() <= 0) {
            throw new BlogException("博客不存在");
        }
        return getUserInfo(blogInfo.getUserId());
    }


}
